const { Sequelize } = require('sequelize');
require('dotenv').config();

// 从环境变量获取数据库配置，如果没有则使用默认值
const DB_HOST = process.env.DB_HOST || 'localhost';
const DB_PORT = process.env.DB_PORT || '3306';
const DB_NAME = process.env.DB_NAME || 'biaowang';
const DB_USER = process.env.DB_USER || 'root';
const DB_PASSWORD = process.env.DB_PASSWORD || '';

// 创建 Sequelize 实例
const sequelize = new Sequelize(DB_NAME, DB_USER, DB_PASSWORD, {
  host: DB_HOST,
  port: DB_PORT,
  dialect: 'mysql',
  logging: process.env.NODE_ENV === 'development' ? console.log : false,
  pool: {
    max: 5,
    min: 0,
    acquire: 30000,
    idle: 10000
  },
  define: {
    timestamps: true, // 默认为模型添加 createdAt 和 updatedAt 字段
    underscored: true, // 使用下划线命名法 (snake_case) 而不是驼峰命名法 (camelCase)
    freezeTableName: true // 不自动将表名变为复数形式
  }
});

// 测试数据库连接
const testConnection = async () => {
  try {
    await sequelize.authenticate();
    console.log('MySQL数据库连接成功');
    return true;
  } catch (error) {
    console.error('MySQL数据库连接失败:', error);
    return false;
  }
};

module.exports = {
  sequelize,
  testConnection
};